import {
  Controller,
  Post,
  HttpCode,
  Body,
  UsePipes,
  HttpStatus,
  HttpException,
  Get,
  Render,
} from '@nestjs/common';
import { RegionService } from './region.service';
import { DtoPipe } from '../common/pipe/dto.pipe';
import { RegionInsertDto } from './dto/region.insert.dto';
import { RegionSearchDto } from './dto/region.search.dto';
import { ResultListDto } from '../common/dto/result.list.dto';
import { idPidToTree } from '../common/utils/tool';
import { RegionEntity } from './region.entity';

@Controller('/region')
export class RegionController {
  constructor(private readonly regionService: RegionService) {}

  // 地区代码
  @Get()
  @Render('system/region')
  welcome() {
    return {
      title: '地区代码',
    };
  }

  // 分页列表
  @Post('/list')
  @UsePipes(DtoPipe)
  @HttpCode(HttpStatus.OK)
  async list(@Body() bodys: RegionSearchDto): Promise<any> {
    const list: ResultListDto = await this.regionService.pagination(bodys);
    return list;
  }

  // 序列化
  @Post('/serialization')
  @UsePipes(DtoPipe)
  @HttpCode(HttpStatus.OK)
  async serialization(): Promise<any> {
    const regionlist: RegionEntity[] = await this.regionService.findAll();
    const regionTree = idPidToTree(regionlist, 'id', 'parent_id');
    return regionTree;
  }

  // 新增
  @Post('/insert')
  @UsePipes(DtoPipe)
  @HttpCode(HttpStatus.OK)
  async insert(@Body() bodys: RegionInsertDto): Promise<any> {
    try {
      const data: boolean = await this.regionService.save(bodys);
      if (!data) {
        throw new HttpException({ message: '当前id不存在数据库中' }, 502);
      }
      return data;
    } catch (error) {
      throw new HttpException(error.response, error.status);
    }
  }
}
